<template>
    <div id="parent">
        <form action="" class="layui-form" lay-filter="form" :form="form" enctype="multipart/form-data">
            <div class="layui-form-item text">
                添加公告：
            </div>
            <div class="layui-form-item input">
                <input
                        type="text"
                        class="layui-input"
                        name="title"
                        lay-verify="required"
                        onkeydown="if(event.keyCode==13)return false;"
                        autocomplete="off"
                        placeholder="请输入标题"
                        :value="msg.title">
            </div>
            <div class="layui-form-item textarea">
                <textarea
                        class="layui-textarea"
                        name="text"
                        id="text"
                        lay-verify="required"
                        autocomplete="off"
                        placeholder="多行输入" :value="msg.text"></textarea>
            </div>
            <div class="layui-form-item">
                <div class="layui-form-label label">图片上传：</div>
                <input type="button" class="layui-btn layui-btn-normal color" id="selectImg" value="选择图片">
                <!--<input type="button" class="layui-btn color"  v-show="isShowButton1" value="点击上传">-->
                <div class="layui-input-block" id="img"></div>
            </div>
            <div class="layui-form-item">
                <div class="layui-form-label label">附件上传：</div>
                <input type="button" class="layui-btn layui-btn-normal color" id="selectFile" value="选择文件">
                <!--<input type="button" class="layui-btn color"  v-show="isShowButton2" value="点击上传">-->
                <table class="layui-table">
                    <thead>
                    <tr><th>文件名</th>
                        <th>大小</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr></thead>
                    <tbody id="file"></tbody>
                </table>
            </div>
            <div class="layui-form-item radio">
                <div class="layui-form-label layui-inline label">公告对象：</div>
                <div class="layui-inline">
                    <input type="radio" name="target" value="1" title="全平台" :checked="msg.target === 1 || 'checked'">
                    <input type="radio" name="target" value="2" title="公司内" :checked="msg.target === 2">
                    <input type="radio" name="target" value="3" title="我的下级" :checked="msg.target === 3">
                </div>
            </div>
            <div class="layui-form-item buttons">
                <div class="layui-input-block">
                    <input type="button" lay-submit lay-filter="Submit"  class="layui-btn layui-btn-primary" :class="{active:isActive}" value="确认提交">
                    <input type="button" class="layui-btn layui-btn-primary " @click="cancel" :class="{active:!isActive}" value="取消">
                </div>
            </div>
        </form>

    </div>
</template>

<script>
    import $ from 'jQuery'
    export default {
        name: "addAnnouncement",
        props:['urls','isActive','msg'],
        data(){
          return {
             imgUrl:[],
             fileUrl:[],
          }
        },
        created:function(){
            var _this = this;
            _this.$nextTick(function() {
                //upload img&file
                layui.use(['upload', 'form'], function () {
                    var upload = layui.upload;
                    var form = layui.form;
                    //图片上传
                    var uploadListIns = upload.render({
                        elem: '#selectImg'
                        , url: _this.urls.announcementManagement.imgUpload
                        , accept: 'images'
                        , multiple: true
                        // , auto: false
                        // , bindAction: '#upload'
                        , number: 9
                        ,field:'image'
                        , done: function (res, index, upload) {
                            _this.imgUrl.push(...res.imgUrl);//将返回的图片路径储存。
                            if (res.code === 1) { //上传成功
                                var tr = $('#img').find('div#upload-' + index)
                                    , tds = tr.children();
                                tds.eq(1).html('<span style="color: #5FB878;">上传成功</span>');
                                tds.eq(2).html(''); //清空操作
                                return delete this.files[index]; //删除文件队列已经上传成功的文件
                            }
                            this.error(index, upload);
                        },
                        error: function (index, upload) {
                            var ele = $('#img').find('div#upload-' + index)
                                , tds = ele.children();
                            tds.eq(1).html('<span style="color: #FF5722;">上传失败</span>');
                            tds.eq(2).find('.demo-reload').removeClass('layui-hide'); //显示重传
                            console.error('图片上传错误')
                        },
                        choose: function (obj) {
                            _this.isShowButton1 = true;
                            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                            //读取本地文件
                            obj.preview(function (index, file, result) {
                                var ele = $(['<div id="upload-' + index + '">'
                                    , '<img src=' + result + '>'
                                    , '<div>等待上传</div>'
                                    , '<div>'
                                    , '<input type="button" class="layui-btn layui-btn-xs demo-reload layui-hide color" value="重传">'
                                    , '<input type="button" class="layui-btn layui-btn-xs layui-btn-danger demo-delete color" value="删除">'
                                    , '</div>'
                                    , '</div>'].join(''));
                                //单个重传
                                ele.find('.demo-reload').on('click', function () {
                                    obj.upload(index, file);
                                });

                                //删除
                                ele.find('.demo-delete').on('click', function () {
                                    delete files[index]; //删除对应的文件
                                    ele.remove();
                                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                });

                                $('#img').append(ele);
                            });
                        },
                    });
                    //文件上传
                    var uploadListFile = upload.render({
                        elem:'#selectFile'
                        , url: _this.urls.announcementManagement.fileUpload
                        , accept: 'file'
                        , multiple: true
                        // , auto: false
                        // , bindAction: '#upload'
                        ,field:'image'
                        , done: function (res, index, upload) {
                            if(res.code === 1){ //上传成功
                                _this.fileUrl.push(...res.path);//将返回的文件路径储存。
                                var tr = $('#file').find('tr#upload-'+ index)
                                    ,tds = tr.children();
                                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                                tds.eq(3).html(''); //清空操作
                                return delete this.files[index]; //删除文件队列已经上传成功的文件
                            }
                            this.error(index, upload);
                        },
                        error: function (index, upload) {
                            var tr = $('#file').find('tr#upload-' + index)
                                , tds = tr.children();
                            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                            tds.eq(3).find('.file-reload').removeClass('layui-hide'); //显示重传
                            console.error('文件上传错误')
                        },
                        choose: function (obj) {
                            console.log(obj)
                            _this.isShowButton2 = true;
                            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                            //读取本地文件
                            obj.preview(function (index, file, result) {
                                var tr = $(['<tr id="upload-'+ index +'">'
                                    ,'<td>'+ file.name +'</td>'
                                    ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
                                    ,'<td>等待上传</td>'
                                    ,'<td>'
                                    , '<input type="button" class="layui-btn layui-btn-xs file-reload layui-hide color" value="重传">'
                                    , '<input type="button" class="layui-btn layui-btn-xs layui-btn-danger file-delete color" value="删除">'
                                    ,'</td>'
                                    ,'</tr>'].join(''));
                                //单个重传
                                tr.find('.file-reload').on('click', function () {
                                    obj.upload(index, file);
                                });
                                //删除
                                tr.find('.file-delete').on('click', function(){
                                    delete files[index]; //删除对应的文件
                                    tr.remove();
                                    uploadListFile.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                });
                                $('#file').append(tr);
                            });
                        }
                    })
                    form.render()
                })
                //show img&file
                if(!$.isEmptyObject(_this.msg)){
                    var file = _this.msg.files;
                    for(var i=0;i<_this.msg.img.length;i++){
                        let html= $(['<div id="upload-' + i + '">'
                            , '<img src=' + _this.msg.img[i] + '>'
                            , '<div>'
                            , '<input type="button" data-src="'+_this.msg.img[i]+'" data-id="'+_this.msg.id+'" class="layui-btn layui-btn-xs layui-btn-danger delete-img color" value="删除">'
                            , '</div>'
                            , '</div>'].join(''));
                        html.find('img').on('click',function(){
                            var image = '<img src="'+this.src+'" />';
                            layui.use('layer',function(){
                                var layer = layui.layer;
                                layer.open({
                                    type:1,
                                    area:['550px','650px'],
                                    content:image
                                })
                            })
                        });
                        html.find('.delete-img').on('click',function(){
                            var id = $(this).data('id'),src = $(this).data('src');
                            layer.open({
                                content:'删除后不可恢复，请您再次确认删除',
                                yes:function(){
                                    layer.closeAll();
                                    $.post(_this.urls.announcementManagement.delImg,{id:id,src:src},function(msg){
                                        // console.log(msg)
                                        html.remove();
                                        layer.msg('删除成功')
                                    })
                                }
                            })

                        })
                        $('#img').append(html);
                    }
                    for(var j=0;j<_this.msg.files.length;j++){
                        var splitLast = _this.msg.files[j].split(/\./g);//截取尾部格式
                        var last = splitLast[splitLast.length-1];
                        let tr = $(['<tr id="upload-'+ j +'">'
                            ,'<td>'+"文件"+(j+1)+"."+last +'</td>'
                            ,'<td></td>'
                            ,'<td>已上传</td>'
                            ,'<td>'
                            , '<a href="'+_this.msg.files[j]+'" type="button" class="layui-btn layui-btn-xs download-file color">下载</a>'
                            , '<input type="button" data-src="'+_this.msg.files[j]+'" data-id="'+_this.msg.id+'" class="layui-btn layui-btn-xs layui-btn-danger delete-file color" value="删除">'
                            ,'</td>'
                            ,'</tr>'].join(''));
                        tr.find('.delete-file').on('click',function(){
                            var id = $(this).data('id'),src = $(this).data('src');
                            layer.open({
                                content:'删除后不可恢复，请您再次确认删除',
                                yes:function(){
                                    layer.closeAll();
                                    $.post(_this.urls.announcementManagement.delFile,{id:id,src:src},function(msg){
                                        console.log(msg)
                                        tr.remove();
                                        layer.msg('删除成功')
                                    })
                                }
                            })

                        })
                        $('#file').append(tr)
                    }
                }
            });
        },
        computed:{
            form(){
                    var _this = this;
                   _this.$nextTick(function(){
                        layui.use(['form','layer'],function(){
                            var form = layui.form;
                            var layer = layui.layer;
                                form.on('submit',function(res){
                        //删除上传时显示的图片name
                        res.field.files = _this.fileUrl.join(',');
                        res.field.img = _this.imgUrl.join(',');
                        if(_this.msg.id !== undefined){
                            res.field.id = _this.msg.id;
                        }
                        // console.log(res.field)
                        var index = layer.open({
                            content: '请您再次确认提交',
                            yes: function(){
                                layer.closeAll();
                                $.ajax({
                                    url:_this.urls.announcementManagement.announcementUpload,
                                    type:'post',
                                    data:res.field,
                                    success:function(res){
                                        // console.log(res)
                                        layer.msg('上传成功')
                                    },
                                    error:function(){
                                        layer.msg('上传失败，请联系管理员');
                                        console.error('确认提交错误')
                                    }
                                })
                            }
                        });
                        // console.log(res)
                    })
                        })
                   })
            }
        },
        methods:{
            cancel(){//向父元素传递事件
                this.$emit('cancel')
            }
        },
        watch:{
            msg:{
                handle(){
                    console.log(123)
                },
                deep:true

            }
        }
    }
</script>

<style lang="less">
    @import "../../../static/css/style.less";
    #parent{
        padding:28px 0;
        font-size: 14px;
        color: @c6;
        form{
            >div{
                margin-bottom: 15px;
            }
            .text{
                line-height: 21px;
            }
            .input{
                width: 354px;
            }
            .textarea{
                width: 800px;
                height: 272px;
                overflow: hidden;
                textarea{
                    width: 100%;
                    min-width: 100%;
                    max-width: 100%;
                    height: 100%;
                    min-height: 100%;
                    max-height: 100%;
                    resize: none;
                    padding: 5px;
                }
            }
            #img{
                width: 100%;
                height: auto;
                margin-left: 0;
                .df;
                flex-wrap: wrap;
                >div{
                    padding: 10px;
                    img{
                        width: 200px;
                        height: 160px;
                        cursor: pointer;
                    }
                    >div:nth-child(2){
                        line-height: 30px;
                    }
                }

            }
            .label{
                width: 90px;
                text-align: left;
                padding-left: 0;
            }
            .radio{
                .df;
                input[type='radio']{
                    -webkit-appearance: radio;
                }
                .layui-form-radio{
                    i{
                        color: #e11e27;
                        font-size: 14px;
                    }
                }
            }
        }
    }
    .color{
        color: @cf!important;
    }
</style>